import { defineStore } from 'pinia'
import { keyUser, valueUser } from '@/api/data'

export const useNavigationStore = defineStore('navigation', {
  state: () => ({
    mode: 'classic', // 默认使用 Win10 导航模式
    settings: {
      sidebarPosition: 'left',
      sidebarWidth: 240,
      autoCollapse: false,
      showIcons: true,
      showBreadcrumb: true,
      showTabs: true,
      showTabNav: true, // 显示Tab标签页导航
      showFavorites: true, // 显示智能收藏夹
      showFloatingBall: true, // 显示悬浮工具球
      enableGesture: true, // 启用鼠标手势
      enablePinyinNav: true, // 启用拼音导航
      fixedHeader: true,
      themeColor: '#409eff',
      darkMode: false,
      compactMode: false
    },
    menuCollapsed: false,
    activeModule: '',
    openedTabs: [],
    commandPanelVisible: false,
    favoriteMenus: [],
    recentVisits: [], // 最近访问
    gestureEnabled: true, // 手势导航启用状态
    quickNavVisible: false // 快速导航面板显示状态
  }),

  getters: {
    sidebarWidth: (state) => state.menuCollapsed ? 64 : state.settings.sidebarWidth,
    
    isClassicMode: (state) => state.mode === 'classic',
    isTopbarMode: (state) => state.mode === 'topbar',
    isWorkspaceMode: (state) => state.mode === 'workspace',
    isCommandMode: (state) => state.mode === 'command',
    isDockMode: (state) => state.mode === 'dock',
    isCardMode: (state) => state.mode === 'card',
    isTabsMode: (state) => state.mode === 'tabs',
    isFavoritesMode: (state) => state.mode === 'favorites',
    isPinyinMode: (state) => state.mode === 'pinyin',
    isGestureMode: (state) => state.mode === 'gesture',
    isFloatingMode: (state) => state.mode === 'floating'
  },

  actions: {
    async setMode(mode) {
      this.mode = mode
      await this.saveToServer()
    },

    async updateSettings(settings) {
      this.settings = { ...this.settings, ...settings }
      await this.saveToServer()
    },

    toggleSidebar() {
      this.menuCollapsed = !this.menuCollapsed
    },

    setActiveModule(module) {
      this.activeModule = module
    },

    addTab(tab) {
      const exists = this.openedTabs.find(t => t.path === tab.path)
      if (!exists) {
        this.openedTabs.push(tab)
      }
    },

    removeTab(path) {
      const index = this.openedTabs.findIndex(t => t.path === path)
      if (index > -1) {
        this.openedTabs.splice(index, 1)
      }
    },

    clearTabs() {
      this.openedTabs = []
    },

    toggleCommandPanel() {
      this.commandPanelVisible = !this.commandPanelVisible
    },

    async addFavorite(menu) {
      if (!this.favoriteMenus.find(m => m.path === menu.path)) {
        this.favoriteMenus.push(menu)
        await this.saveToServer()
      }
    },

    async removeFavorite(path) {
      const index = this.favoriteMenus.findIndex(m => m.path === path)
      if (index > -1) {
        this.favoriteMenus.splice(index, 1)
        await this.saveToServer()
      }
    },

    async addRecentVisit(page) {
      // 移除已存在的
      this.recentVisits = this.recentVisits.filter(v => v.path !== page.path)
      
      // 添加到开头
      this.recentVisits.unshift({
        ...page,
        lastVisit: Date.now()
      })
      
      // 最多保留20条
      if (this.recentVisits.length > 20) {
        this.recentVisits = this.recentVisits.slice(0, 20)
      }
      
      await this.saveToServer()
    },

    toggleQuickNav() {
      this.quickNavVisible = !this.quickNavVisible
    },

    async toggleGesture() {
      this.gestureEnabled = !this.gestureEnabled
      await this.saveToServer()
    },

    async resetSettings() {
      this.mode = 'classic'
      this.settings = {
        sidebarPosition: 'left',
        sidebarWidth: 240,
        autoCollapse: false,
        showIcons: true,
        showBreadcrumb: true,
        showTabs: true,
        fixedHeader: true,
        themeColor: '#409eff',
        darkMode: false,
        compactMode: false
      }
      await this.saveToServer()
    },

    async loadFromServer() {
      try {
        // 加载导航设置
        const response = await keyUser('navigation_settings')
        if (response && response.code === 200 && response.data) {
          let data = response.data
          if (typeof data === 'string') {
            data = JSON.parse(data)
          } else if (data.value) {
            data = JSON.parse(data.value)
          }
          // 默认使用 win10 模式，而不是 classic
          this.mode = data.mode || 'classic'
          this.settings = { ...this.settings, ...data.settings }
          this.gestureEnabled = data.gestureEnabled !== undefined ? data.gestureEnabled : true
        }
      } catch (error) {
        console.error('Failed to load navigation settings:', error)
      }

      try {
        // 加载收藏菜单
        const response = await keyUser('favorite_menus')
        if (response && response.code === 200 && response.data) {
          let data = response.data
          if (typeof data === 'string') {
            data = JSON.parse(data)
          } else if (data.value) {
            data = JSON.parse(data.value)
          }
          this.favoriteMenus = Array.isArray(data) ? data : []
        }
      } catch (error) {
        console.error('Failed to load favorite menus:', error)
      }

      try {
        // 加载最近访问
        const response = await keyUser('recent_visits')
        if (response && response.code === 200 && response.data) {
          let data = response.data
          if (typeof data === 'string') {
            data = JSON.parse(data)
          } else if (data.value) {
            data = JSON.parse(data.value)
          }
          this.recentVisits = Array.isArray(data) ? data : []
        }
      } catch (error) {
        console.error('Failed to load recent visits:', error)
      }
    },

    async saveToServer() {
      try {
        // 保存导航设置
        await valueUser('navigation_settings', JSON.stringify({
          mode: this.mode,
          settings: this.settings,
          gestureEnabled: this.gestureEnabled
        }))
      } catch (error) {
        console.error('Failed to save navigation settings:', error)
      }

      try {
        // 保存收藏菜单
        await valueUser('favorite_menus', JSON.stringify(this.favoriteMenus))
      } catch (error) {
        console.error('Failed to save favorite menus:', error)
      }

      try {
        // 保存最近访问
        await valueUser('recent_visits', JSON.stringify(this.recentVisits))
      } catch (error) {
        console.error('Failed to save recent visits:', error)
      }
    }
  }
})
